//
//  BKTabBar.swift
//  微博
//
//  Created by mac on 16/8/9.
//  Copyright © 2016年 xbk. All rights reserved.
//

import UIKit

class BKTabBar: UITabBar {

    //撰写按钮的闭包
    var composeButtonClosure: (()->())?

    //  MARK: -- 懒加载
    private lazy var composeButton :UIButton = {
    
        let button = UIButton()
        
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Highlighted)
        
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: .Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Highlighted)
        
        //设置点击事件
        button.addTarget(self, action: "composeButtonAction", forControlEvents: .TouchUpInside)
        
        
        //设置大小
        button.sizeToFit()
        
        return button
    }()
    
    //构造函数创建对象
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        setUPUI()
    }

    //当使用xib和storyBoad的时候调用该方法
    required init?(coder aDecoder: NSCoder) {
        //fatalError("init(coder:) has not been implemented")
        super.init(coder: aDecoder)
        setUPUI()
    }
    
    //  MARK: -- 添加compose按钮视图
    private func setUPUI() {
    
        addSubview(composeButton)
    }
    
    //  MARK: -- 点击事件
    @objc private func composeButtonAction() {
    
        composeButtonClosure?()
    }
    
    
    
    //调整子控件的布局
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        composeButton.centerX = width * 0.5
        composeButton.centerY = height * 0.5
        
        let itemWidth = width/5
        
        var index = 0
        
        for value in subviews{
        
            if value.isKindOfClass(NSClassFromString("UITabBarButton")!){
            
                value.width = itemWidth
                value.x = CGFloat(index) * itemWidth
                
                index++
                
                if index == 2 {
                
                    index++
                }
                
            }
            
            
        }
    }
    
    
}
